package ncs.admin.action;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;

import javax.servlet.ServletContext;

import ncs.admin.database.CourseDAO;
import ncs.common.model.Course;
import ncs.common.model.RSResult;
import ncs.common.model.SessionStore;
import ncs.common.model.exception.TeacherNotExistException;
import ncs.common.util.Util;

import org.apache.struts2.ServletActionContext;

import com.alibaba.fastjson.JSON;
import com.opensymphony.xwork2.ActionSupport;

public class CourseAction extends ActionSupport{
	private static final long serialVersionUID = -3263013195626593695L;
	private InputStream inputStream;
	private String query;
	private RSResult result;
	public InputStream getInputStream() {
		return inputStream;
	}
	public void setInputSteam(InputStream inputStream) {
		this.inputStream = inputStream;
	}
	public String getQuery() {
		return query;
	}
	public void setQuery(String query) {
		this.query = query;
	}
	public String addCourse() throws Exception{
		Course c=this.createCourse();
		CourseDAO dao=new CourseDAO();
		result=new RSResult();
		try
		{
			dao.addCourse(c);
			ServletContext context=ServletActionContext.getServletContext();
			File dir=new File(context.getRealPath("/upload/"+c.getCourse_id()));
			if(!dir.exists())
				dir.mkdirs();
		}catch(TeacherNotExistException e)
		{
			result.setCode(2);
			result.setMsg("教师不存在");
		}
		catch(Exception ex)
		{
			result.setCode(3);
			result.setMsg("服务器忙请稍后再试");
		}
		String json=JSON.toJSONString(result);
		inputStream=new ByteArrayInputStream(json.getBytes("UTF-8"));
		return SUCCESS;
	}
	private Course createCourse()
	{
		Course course=JSON.parseObject(query, Course.class);
		//这里只是测试用，正式应该从SESSION中获取信息
		SessionStore store=Util.getSessionStore();
		course.setAdmin_db_id(store.getUser().getDbID());
		course.setAdmin_name(store.getUserName());
		course.setCourse_id(0);
		course.setCreate_time(null);
		course.setStudent_count(0);
		course.setTeacher_name("AA");
		return course;
	}
}
